﻿using EMS.system.Common;
using EMS.system.Entityies.MasterData.SupplierManagementModel;
using EMS.system.Entityies.WarehouseManagement.SupplierReturnModel;
using EMS.system.IEntityAppService.MasterData.SupplierManagementIService.SupplierManagementDto;
using EMS.system.IEntityAppService.MasterData.SupplierReturnService;
using EMS.system.IEntityAppService.MasterData.SupplierReturnService.SupplierReturnDto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace EMS.system.EntityAppService.MasterData.SupplierReturnService
{
    public class SupplierReturnAppService:ApplicationService,ISupplierReturnAppService
    {
        private static Object obj = new Object();
        /// <summary>
        /// 供应商退货仓储
        /// </summary>
        private readonly IRepository<SupplierReturn,int> _supplierReturnRepository;
        /// <summary>
        /// 供应商管理仓储
        /// </summary>
        private readonly IRepository<SupplierManagement, int> _supplierManageMentRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="supplierReturnRepository"></param>
        /// <param name="supplierManageMentRepository"></param>
        public SupplierReturnAppService(IRepository<SupplierReturn, int> supplierReturnRepository, IRepository<SupplierManagement, int> supplierManageMentRepository)
        {
            _supplierReturnRepository = supplierReturnRepository;
            _supplierManageMentRepository= supplierManageMentRepository;
        }
        /// <summary>
        /// 获取供应商退货分页 查询 显示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="returnName"></param>
        /// <returns></returns>
        public async Task<PagedResult> GetSupplierReturnList(int pageIndex,int pageSize, string? returnCode,string ? returnName)
        {
            var predicate = PredicateBuilder.New<SupplierReturn>(true);
            if (!string.IsNullOrEmpty(returnCode))
            {
                predicate = predicate.And(m => m.ReturnCode.Contains(returnCode));
            }
            if (!string.IsNullOrEmpty(returnName))
            {
                predicate = predicate.And(m => m.ReturnName.Contains(returnName));
            }
            var supplierReturn = from a in (await _supplierReturnRepository.GetListAsync(predicate))
                            join b in _supplierManageMentRepository.GetListAsync().Result on a.SupplierManagementCode equals b.SupplierManagementCode
                            select new SupplierReturnDTO
                            {
                                Id=a.Id,
                                ReturnCode=a.ReturnCode,
                                ReturnName=a.ReturnName,
                                PurchaseCode=a.PurchaseCode,
                                ReturnDate=a.ReturnDate,
                                Dstatus=a.Dstatus,
                                SupplierManagementCode=a.SupplierManagementCode,
                                SupplierName=b.SupplierName,
                                SupplierAbbreviation=b.SupplierAbbreviation,
                                SupplierGrade=b.SupplierGrade,
                                SupplierPhone=b.SupplierPhone,
                                SupplierScore=b.SupplierScore,
                            };
            //var dto = await _supplierReturnRepository.GetListAsync(predicate);
            PagedResult result = new PagedResult();
            result.PageCount = (int)Math.Ceiling((double)(supplierReturn.Count() ==0 ? 1 : supplierReturn.Count()) / pageSize);
            result.PageSize = pageSize;
            result.CurrentPage = pageIndex;
            result.RowCount= supplierReturn.Count();
            result.Queryable= supplierReturn.Skip((pageIndex-1)*pageSize).Take(pageSize).AsQueryable();
            return result;
        }
        /// <summary>
        /// 获取供应商管理列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<SelectSupplierManagementDto>> GetSupplierManagement()
        {
            var supplierManagement = await _supplierManageMentRepository.GetListAsync();
            var supplierManagementDTO =supplierManagement.MapToList< SelectSupplierManagementDto> ();
            return supplierManagementDTO;

        }
        ///// <summary>
        ///// redis集群
        ///// </summary>
        ///// <returns></returns>
        ////缓存击穿 （lock锁+2次判断）
        //public async Task<List<SelectSupplierManagementDto>> GetSupplierManagementListRedis()
        //{
        //    //根据Key值，获取学生list集合
        //    var supplierManagementList = EMS.system.Common.RedisHelper.Get<List<SelectSupplierManagementDto>>("SupplierManagementListKey");
        //    if (supplierManagementList == null)
        //    {
        //        lock (obj)
        //        {
        //            if (supplierManagementList == null)
        //            {
        //                //从数据库中取出学生集合
        //                supplierManagementList = GetSupplierManagement().Result;
        //                var seconds = 30000 + new Random().Next(1, 1000);
        //                //将学生集合缓存在Redis中，key值为：StudentList
        //                EMS.system.Common.RedisHelper.Set("SupplierManagementListKey", supplierManagementList, DateTime.Now.AddDays(1));
        //            }
        //        }
        //    }
        //    return supplierManagementList;
        //}

        /// <summary>
        /// 添加供应商退货
        /// </summary>
        /// <param name="supplierReturnDTO"></param>
        /// <returns></returns>
        public async Task<int> CreateSupplierReturn(SupplierReturnDTO supplierReturnDTO)
        {
            var returnName= _supplierReturnRepository.CountAsync(m=>m.ReturnName==supplierReturnDTO.ReturnName&&m.Id!=supplierReturnDTO.Id).Result;
            if (returnName>0)
            {
                return -1;
            }
            var purchaseCode=_supplierReturnRepository.CountAsync(m=>m.PurchaseCode==supplierReturnDTO.PurchaseCode && m.Id != supplierReturnDTO.Id).Result;
            if (purchaseCode > 0) 
            {
                return -2;
            }
            var supplierReturn = supplierReturnDTO.MapTo<SupplierReturn>();
            await _supplierReturnRepository.InsertAsync(supplierReturn);
            return 1;
        }
        /// <summary>
        /// 删除供应商退货
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteSupplierReturn(string ids)
        {
            string[] array=ids.Split(',');
            await _supplierReturnRepository.DeleteAsync(x=> ids.Contains(x.Id.ToString()));
            return 1;
        }
        /// <summary>
        /// 获取供应商退货主键id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SupplierReturnDTO> GetSupplierReturnById(int id)
        {
            var supplierReturn = await _supplierReturnRepository.GetAsync(id);
            var supplierReturnDTO = supplierReturn.MapTo<SupplierReturnDTO>();
            return supplierReturnDTO;
        }
        /// <summary>
        /// 更新供应商退货
        /// </summary>
        /// <param name="supplierReturnDTO"></param>
        /// <returns></returns>
        public async Task<int> UpdateSupplierReturn(SupplierReturnDTO supplierReturnDTO)
        {
            var returnCode = _supplierReturnRepository.CountAsync(m => m.ReturnCode == supplierReturnDTO.ReturnCode && m.Id != supplierReturnDTO.Id).Result;
            if (returnCode > 0)
            {
                return -1;
            }
            var returnName = _supplierReturnRepository.CountAsync(m => m.ReturnName == supplierReturnDTO.ReturnName && m.Id != supplierReturnDTO.Id).Result;
            if (returnName > 0)
            {
                return -2;
            }
           
            var supplierReturn=supplierReturnDTO.MapTo<SupplierReturn>();
            await _supplierReturnRepository.UpdateAsync(supplierReturn);
            return 1;
        }
    }
}
